package org.jeecg.modules.salary.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.DataUtils;
import org.jeecg.modules.salary.entity.SalaryFields;
import org.jeecg.modules.salary.mapper.SalaryFieldsMapper;
import org.jeecg.modules.salary.service.ISalaryAdjustService;
import org.jeecg.modules.salary.service.ISalaryFieldsService;
import org.jeecg.modules.salary.service.ISalarySubService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.transaction.Transactional;
import java.util.*;

/**
 * @Description: 薪资管理
 * @Author: jeecg-boot
 * @Date:   2020-08-19
 * @Version: V1.0
 */
@Slf4j
@Service
@Transactional(rollbackOn = RuntimeException.class, value = Transactional.TxType.REQUIRED)
public class SalaryFieldsServiceImpl extends ServiceImpl<SalaryFieldsMapper, SalaryFields> implements ISalaryFieldsService {

    @Autowired
    SalaryFieldsMapper  salaryFieldsMapper;

    @Autowired
    private ISalaryAdjustService salaryAdjustService;

    @Autowired
    private ISalarySubService salarySubService;

    
    @Override
    public String getMaxField() {
        return salaryFieldsMapper.getMaxField();
    }

    @Override
    public List<SalaryFields> list() {
        LambdaQueryWrapper<SalaryFields> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.isNull(SalaryFields::getDeletedAt);
        queryWrapper.eq(SalaryFields::getHasChildren,CommonConstant.STATUS_0);
        queryWrapper.orderByAsc(SalaryFields::getFieldSort);
        return list(queryWrapper);
    }

    @Override
    public String getFieldValue(String userId, String fieldId) {
        String fieldValue = "";
        String max = salaryAdjustService.getMaxMoney(userId,fieldId);
        if(StringUtils.isNotEmpty(max)){
            fieldValue = max;
        }else{
            SalaryFields salaryFields = this.getById(fieldId);
            fieldValue = salaryFields.getFieldDefault();
        }
        return fieldValue;
    }

    @Override
    public List<SalaryFields> listParentAll() {
        LambdaQueryWrapper<SalaryFields> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.isNull(SalaryFields::getDeletedAt);
        queryWrapper.orderByAsc(SalaryFields::getFieldSort);
        queryWrapper.isNull(SalaryFields::getFieldParent);
        return list(queryWrapper);
    }

    @Override
    public List<SalaryFields> getByFieldParent(String id) {
        LambdaQueryWrapper<SalaryFields> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SalaryFields::getFieldParent,id);
        queryWrapper.isNull(SalaryFields::getDeletedAt);
        return list(queryWrapper);
    }


    @Override
    public String insert(SalaryFields salaryFields){
        String fieldName = "";
        String fieldCode = salaryFieldsMapper.getMaxField();
        int num = 0;
        if(StringUtils.isNotEmpty(fieldCode) && fieldCode.contains("field")){
            num = Integer.valueOf(fieldCode.substring(fieldCode.indexOf("_") + 1));
            num = num+1;
            fieldName = "field_"+ num;
        }else{
            fieldName = "field_1";
        }
        salaryFields.setFieldCode(fieldName);
        //添加子类
        if(StringUtils.isNotEmpty(salaryFields.getFieldParent())){
            //更新父类
            SalaryFields salaryField =  this.getById(salaryFields.getFieldParent());
            if(Objects.nonNull(salaryField) && !CommonConstant.STATUS_1.equals(salaryField.getHasChildren())){
                salaryField.setFieldDefault(CommonConstant.STATUS_0);
                salaryField.setHasChildren(CommonConstant.STATUS_1);
                salaryFieldsMapper.updateById(salaryField);
            }
            salaryFields.setFieldSort(Integer.valueOf(getMaxFieldSort())+1);
            salaryFields.setFieldDefaultSet(CommonConstant.STATUS_1);
            salaryFields.setFieldFormat(CommonConstant.STATUS_1);
            salaryFields.setFieldDefault(CommonConstant.STATUS_0);
            salaryFields.setFieldType(salaryField.getFieldType());
        }
        //默认值 处理数据
        if(CommonConstant.STATUS_1.equals(salaryFields.getFieldDefaultSet()) && StringUtils.isEmpty(salaryFields.getFieldParent())){
            String fieldDefault = salaryFields.getFieldDefault();
            fieldDefault= DataUtils.getNumber(fieldDefault,salaryFields.getFieldFormat());
            fieldDefault = DataUtils.keepPrecision(fieldDefault,salaryFields.getFieldDecimal());
            salaryFields.setFieldDefault(fieldDefault);
        }else if(CommonConstant.STATUS_2.equals(salaryFields.getFieldDefaultSet())){
            String code = returnT(salaryFields.getFieldSource());
            if(CommonConstant.STATUS_0.equals(code)){
                return "0";
            }else{
                salaryFields.setFieldSource(code);
            }
        }
        salaryFields.setHasChildren(CommonConstant.STATUS_0);
        save(salaryFields);
        salarySubService.insertField(fieldName);
        return "1";
    }

    @Override
    public String getMaxFieldSort() {
        String number = "";
        number =  salaryFieldsMapper.getMaxFieldSort();
        if(StringUtils.isEmpty(number)){
            number = CommonConstant.STATUS_1;
        }
        return number;
    }

    @Override
    public String deleteByIds(List<String> ids) {
        for(String str : ids){
            //查询是否含有子项
            LambdaQueryWrapper<SalaryFields> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(SalaryFields::getFieldParent,str);
            queryWrapper.isNull(SalaryFields::getDeletedAt);
            List<SalaryFields> list = this.list(queryWrapper);
            if(list.size()>0){
                return "0";
            }
        }
        for(String id : ids){
            //查询数据
            SalaryFields salaryFields = this.getById(id);
            String fieldParent = salaryFields.getFieldParent();
            //判断是否含有父ID
            if(StringUtils.isNotEmpty(fieldParent)){
                LambdaQueryWrapper<SalaryFields> query = new LambdaQueryWrapper();
                query.eq(SalaryFields::getFieldParent,fieldParent);
                query.isNull(SalaryFields::getDeletedAt);
                //查询数据
                List<SalaryFields> fieldsList = this.list(query);
                //判断父类下有几条数据
                if(fieldsList.size()<2){
                    SalaryFields  salary =  this.getById(fieldParent);
                    salary.setHasChildren(CommonConstant.STATUS_0);
                    salary.setFieldDefault(CommonConstant.STATUS_0);
                    this.updateById(salary);
                }
            }
            //添加删除时间
            salaryFields.setDeletedAt(new Date());
            this.updateById(salaryFields);
            salarySubService.deleteField(salaryFields.getFieldCode());
        }
        return "1";
    }

    @Override
    public String update(SalaryFields salaryFields) {
        //获取旧数据
        SalaryFields oldSalaryFields = getById(salaryFields.getId());
        String oldFieldParent  = oldSalaryFields.getFieldParent();
        String newFieldParent  = salaryFields.getFieldParent();
        //是否含有子类
        String hasChildren  = salaryFields.getHasChildren();
        if(CommonConstant.STATUS_1.equals(hasChildren)){
            salaryFields.setFieldDefault(CommonConstant.STATUS_0);
            updateById(salaryFields);
            return "1";
        }
        //判断旧数据不含父ID，新数据有ID（移动）
        if(StringUtils.isEmpty(oldFieldParent) && StringUtils.isNotEmpty(newFieldParent)){
            //查询父类
            SalaryFields salaryField =  getById(salaryFields.getFieldParent());
            //判断是否含有子类
            if(!CommonConstant.STATUS_1.equals(salaryField.getHasChildren())){
                salaryField.setFieldDefault(CommonConstant.STATUS_0);
                salaryField.setHasChildren(CommonConstant.STATUS_1);
                //更新父类数据
                updateById(salaryField);
            }
            updateById(salaryFields);
            return "1";
        }

        //判断旧数据含父ID，新数据有父ID ，不相等（移动）
        if(StringUtils.isNotEmpty(oldFieldParent) && StringUtils.isNotEmpty(newFieldParent) && !oldFieldParent.equals(newFieldParent)){
            //查询旧父类
            SalaryFields oldSalaryField =  getById(oldFieldParent);
            //查询新父类
            SalaryFields newSalaryField =  getById(newFieldParent);
            //判断是否含有子类
            if(!CommonConstant.STATUS_1.equals(newSalaryField.getHasChildren())){
                newSalaryField.setFieldDefault(CommonConstant.STATUS_0);
                newSalaryField.setHasChildren(CommonConstant.STATUS_1);
                //更新父类数据
                salaryFieldsMapper.updateById(newSalaryField);
            }
            List<SalaryFields> dataList  = salaryFieldsMapper.getListByParent(oldFieldParent);
            if(dataList.size()<2){
                oldSalaryField.setHasChildren(CommonConstant.STATUS_0);
                oldSalaryField.setFieldParent(null);
                salaryFieldsMapper.updateById(oldSalaryField);
            }
            updateById(salaryFields);
            return "1";
        }

        //默认值 处理数据
        if(CommonConstant.STATUS_1.equals(salaryFields.getFieldDefaultSet())){
            String fieldDefault = salaryFields.getFieldDefault();
            fieldDefault= DataUtils.getNumber(fieldDefault,salaryFields.getFieldFormat());
            fieldDefault = DataUtils.keepPrecision(fieldDefault,salaryFields.getFieldDecimal());
            salaryFields.setFieldDefault(fieldDefault);
        }
        else if(CommonConstant.STATUS_2.equals(salaryFields.getFieldDefaultSet())){
            String code = returnT(salaryFields.getFieldSource());
            if(CommonConstant.STATUS_0.equals(code)){
                return "0";
            }else{
                salaryFields.setFieldSource(code);
                salaryFields.setFieldDefault(CommonConstant.STATUS_0);
            }
        }
        updateById(salaryFields);
        return "1";

    }

    @Override
    public String deleteById(String id) {
        //查询是否含有子项
        LambdaQueryWrapper<SalaryFields> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SalaryFields::getFieldParent,id);
        queryWrapper.isNull(SalaryFields::getDeletedAt);
        List<SalaryFields> list = this.list(queryWrapper);
        if(list.size()>0){
            return "0";
        }
        //查询数据
        SalaryFields salaryFields = this.getById(id);
        String fieldParent = salaryFields.getFieldParent();
        //判断是否含有父ID
		if(StringUtils.isNotEmpty(fieldParent)){
			LambdaQueryWrapper<SalaryFields> query = new LambdaQueryWrapper();
            query.eq(SalaryFields::getFieldParent,fieldParent);
            query.isNull(SalaryFields::getDeletedAt);
			//查询数据
			List<SalaryFields> fieldsList = this.list(query);
			//判断父类下有几条数据
			if(fieldsList.size()<2){
				SalaryFields  salary =  this.getById(fieldParent);
				salary.setHasChildren(CommonConstant.STATUS_0);
                salary.setFieldDefault(CommonConstant.STATUS_0);
				this.updateById(salary);
			}
		}
		//添加删除时间
		salaryFields.setDeletedAt(new Date());
		this.updateById(salaryFields);
        salarySubService.deleteField(salaryFields.getFieldCode());
        return "1";
    }

    //处理计算公式
    public String returnT(String fieldSource){
        Document doc = Jsoup.parse(fieldSource);
        Elements elements = doc.select("span");
        Map<String,String> map = returnMap();
        for (Element element:elements) {
            String fieldCode = "";
            //获取class属性
            String cssClass = element.attr("class");
            String code = element.wholeText().trim();
            boolean flag = DataUtils.specialSymbols(code);
            if(!flag){
                if (cssClass.contains("charachter")) {
                    for(String key :map.keySet()){
                        if(code.equals(key)){
                            fieldCode = map.get(key);
                            element.attr("id",map.get(key));
                        }
                    }
                }
                if(StringUtils.isBlank(fieldCode)){
                    return "0";
                }
            }
        }
        return elements.toString();
    }


    /**
     * 获取 fieldCode，fieldName
     * @return
     */
    public Map<String,String> returnMap(){
        Map<String,String> map = new HashMap<>();
        LambdaQueryWrapper<SalaryFields> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.isNull(SalaryFields::getDeletedAt);
        List<SalaryFields> list = list(queryWrapper);
        for(SalaryFields salaryFields : list){
            map.put(salaryFields.getFieldName(),salaryFields.getFieldCode());
        }
        return  map;
    }

}
